package com.explorex.infra.puma.gateway.netty.rrmp.codec;

import com.explorex.infra.puma.gateway.netty.rrmp.RrmpMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.nio.ByteBuffer;

/**
 * @author: JacceYang
 * @createTime: 2022/09/03 17:31
 * @description: ProxyMessageHandler
 */
@ChannelHandler.Sharable
public class ConnectorEncodeHandler extends MessageToByteEncoder<RrmpMessage> {

    public static final MessageToByteEncoder<RrmpMessage> SHARABLE_INSTANCE = new ConnectorEncodeHandler();

    @Override
    protected void encode(ChannelHandlerContext ctx, RrmpMessage msg, ByteBuf out) throws Exception {
        MessageHeader header = msg.getHeader();
        out.writeByte(header.getMagic());
        byte[] biz = toBytes(header.getBusiness(), 2);
        out.writeBytes(biz);

        out.writeByte(header.getEncryptType());
        byte tmp = (byte) (header.getProtocolVersion() << 2 | header.getQos());
        out.writeByte(tmp);
        byte[] len = toBytes(header.getBodyLength(), 3);
        len[0] = (byte) (len[0] | header.getReservedBits());
        out.writeBytes(len);
        out.writeByte(header.getKeyCheck());
        out.writeBytes(header.getBodyCheck());
        if (msg.getBody() != null) {
            out.writeBytes(msg.getBody());
        }
        return;
    }

    private byte[] toBytes(int i, int len) {
        ByteBuffer b = ByteBuffer.allocate(4);
        b.putInt(i);
        byte[] r = new byte[len];
        for (int index = 0; index < len; index++) {
            r[index] = b.array()[4 - len + index];
        }
        return r;
    }
}